package com.community.config.shiro;

import com.community.entity.Right;
import com.community.service.RoleService;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //注入redis参数
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    //    @Value("${spring.redis.password}")
//    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Resource
    RoleService roleService;

    /**
     * 开启 Shiro 注解(如@RequiresRoles,@RequiresPermissions),
     * 需借助 SpringAOP 扫描使用 Shiro 注解的类,并在必要时进行安全逻辑验证
     * 配置以下两个 bean(DefaultAdvisorAutoProxyCreator 和
     * AuthorizationAttributeSourceAdvisor)
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启 aop 注解支持
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
//        redisManager.setPassword(password);
        redisManager.setTimeout(timeout);
        return redisManager;
    }

    /**
     * cacheManager 缓存 redis实现
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //缓存名称
        redisCacheManager.setPrincipalIdFieldName("account");
        //缓存时间
        redisCacheManager.setExpire(1800);
        return redisCacheManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * 使用的是shiro-redis开源插件
     */
    //会话操作
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * Session Manager
     * 使用的是shiro-redis开源插件
     */
    //会话管理
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }


    @Bean
    public MyShiroRealm myShiroRealm() { //自定义 Realm
        MyShiroRealm shiroRealm = new MyShiroRealm();
        //设置启用缓存，并设置缓存名称
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setAuthorizationCachingEnabled(true);
        shiroRealm.setAuthorizationCacheName("authorizationCache");
        //设置凭证(密码)匹配器
//        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }

    @Bean
    public SecurityManager securityManager() { //安全管理器 SecurityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //注入 Realm
        securityManager.setRealm(myShiroRealm());
        //注入缓存管理器
        securityManager.setCacheManager(cacheManager());
        //注入会话管理器
        securityManager.setSessionManager(sessionManager());

        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
        System.out.println("ShiroConfig.shiroFilterFactory");
        //Shiro 过滤器：权限验证
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();
        //注入 SecurityManager
        shiroFilterFactory.setSecurityManager(securityManager);
        //权限验证：使用 Filter 控制资源(URL)的访问
        shiroFilterFactory.setLoginUrl("/login2");//设置未登录时访问未授权站点跳转
        shiroFilterFactory.setLoginUrl("http://127.0.0.1:8080");//设置未登录时访问未授权站点跳转
        shiroFilterFactory.setSuccessUrl("/index");// 登录成功后要跳转的链接
        shiroFilterFactory.setUnauthorizedUrl("/403"); //没有权限跳转 403 页面
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();//必须使用 LinkedHashMap(有序集合)
        //配置可以匿名访问的资源(URL)：静态资源
        filterChainDefinitionMap.put("/statics/css/**", "anon");
        filterChainDefinitionMap.put("/statics/fonts/**", "anon");
        filterChainDefinitionMap.put("/statics/images/**", "anon");
        filterChainDefinitionMap.put("/statics/js/**", "anon");
        filterChainDefinitionMap.put("/statics/lib/**", "anon");
        filterChainDefinitionMap.put("/statics/upload/**", "anon");

        filterChainDefinitionMap.put("/account", "anon");
        filterChainDefinitionMap.put("/email", "anon");
        filterChainDefinitionMap.put("/register", "anon");
        filterChainDefinitionMap.put("/add", "anon");

        filterChainDefinitionMap.put("/dologin", "anon");
        filterChainDefinitionMap.put("/logout", "logout");//注销过滤器，自动注销

        //配置需要特定权限才能访问的资源(URL)
        //动态授权
        List<Right> rights = roleService.findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                System.out.println("过滤器拦截的url:" + right.getRightUrl() + ",以及对应需要访问的权限:" + right.getRightText());
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightText() + "]");
            }
        }

        //配置认证访问：其他资源(URL)必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "anon"); //必须放在过滤器链的最后面
        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactory;
    }
}
